/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package checker.sdchecker;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.Callable;

/**
 *
 * @author takeshi
 */
public class ReadPartitionTester extends PartitionTester {

    private final File[] selectedFiles;

    public ReadPartitionTester(File root, File[] selectedFiles) throws IOException {
        super(root);
        this.selectedFiles = selectedFiles;
    }

    public ReadPartitionTester(File root, int numberOfThreads, File[] selectedFiles) throws IOException {
        super(root, numberOfThreads);
        this.selectedFiles = selectedFiles;
    }

    public ReadPartitionTester(File root, int numberOfThreads, long size, File[] selectedFiles) throws IOException {
        super(root, numberOfThreads, size);
        this.selectedFiles = selectedFiles;
    }

    @Override
    protected Callable<Void> createJob(final File toUse) {
        return new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                FileInputStream fin = new FileInputStream(toUse);
                try {
                    int offset = 0;
                    byte[] buffer = new byte[1024 * 1024];
                    int read = fin.read(buffer);
                    while (read >= 0 && !isStopped()) {
                        check(buffer, read, offset);
                        offset = (offset + read) % TEST_DATA.length;
                        addBytes(read);
                        if (Thread.currentThread().isInterrupted()) {
                            throw new InterruptedException();
                        }
                        read = fin.read(buffer);
                    }
                    fileFinished();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return null;
                } catch (IOException e) {
                    setError(e);
                } finally {
                    fin.close();
                }
                return null;
            }

            private void check(byte[] buffer, int read, int offset) throws IOException {
                for (int i = 0; i < read; i++) {
                    if (buffer[i] != TEST_DATA[offset + i]) {
                        throw new IOException();
                    }
                }
            }
        };
    }

    @Override
    protected File[] selectFiles(File root) {
        return this.selectedFiles;
    }

    void eraseAllFiles() {
        for(File file: this.selectedFiles){
            file.delete();
        }
    }
}
